<?php
namespace app\admin\controller;

use app\common\utils\Jwt;
use app\common\utils\Token;
use app\common\message\SuccessMessage;
use app\common\exception\TokenException;
use app\common\exception\ImageException;

/**
 * 后台crud以Category模块为模板
 */
class Base extends \think\Controller
{
    protected static $admin;
    protected function _initialize()
    {
        parent::_initialize();
        //检测token
        $token = Token::getBearToken();
        if(!$token){
            throw new TokenException(['msg'=>'请在header中携带token令牌', 'http_code'=>200]);
        }
        try{
            //登录检测
            $admin_id = (new Jwt())->parseToken($token);
            if(empty($admin_id)) {
                throw new TokenException(['http_code'=>200]);
            }
            self::$admin = $admin_id;
            //TODO: 权限验证
        }catch (\Exception $e){
            throw new TokenException(['http_code'=>200]);
        }
    }

    protected function upload_img($type)
    {
        $path = ROOT_PATH.'public';
        $webpath = '/uploads/'.$type;
        if(!is_dir($path.$webpath)){
            mkdir($path.$webpath);
        }
        $file = $this->request->file('img');
        if(empty($file)){
            throw new ImageException(['msg'=>'必须选择图片文件']);
        }
        $info = $file->validate(['size'=>10*1024*1024, 'ext'=>'jpg,jpeg,png,gif'])->move($path.$webpath);
        if (!$info) {
            $msg = "上传出错".$info->getError();
            throw new ImageException(['msg'=>$msg]);
        }
        return $this->ok([$webpath.DS.$info->getSaveName()]);
    }

    protected function upload_imgs($type){
        $data = ['success'=>[], 'error'=>[]];
        $path = ROOT_PATH.'public';
        $webpath = '/uploads/'.$type;
        if(!is_dir($path.$webpath)){
            mkdir($path.$webpath);
        }
        $files = request()->file('imgs');
        if(empty($files)){
            throw new ImageException(['msg'=>'必须选择图片文件']);
        }
        foreach($files as $file){
            $info = $file->validate(['size'=>10*1024*1024, 'ext'=>'jpg,jpeg,png,gif'])->move($path.$webpath);
            if(!$info) {
                $data['error'][] = [
                    'name' => $info->getInfo('name'),
                    'msg' => $info->getError()
                ];
            }else{
                $data['success'][]=$webpath.DS.$info->getSaveName();
            }
        }
        $this->ok($data);
    }

    protected function ok($data=[], $msg='ok'){
        $res = new SuccessMessage($data, $msg);
        return json($res, 200)->send();
    }
}